﻿using System;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;

namespace WordAutomation
{
    class MsWord
    {
        public static readonly string Caption = "Microsoft Word - Application";
        public static IntPtr HWnd { get; private set; }

        public static Word.Application App { get; private set; }

        public static void LoadApplication()
        {
            if (App != null) return;
            App = new Word.Application { Caption = Caption };
            HWnd = Win32.FindWindowByCaption(IntPtr.Zero, Caption);
            ((Word.ApplicationEvents2_Event)App).Quit += OnQuit;
            ((Word.ApplicationEvents3_Event)App).WindowSize += OnSize;
            //((Word.ApplicationEvents4_Event)App).NewDocument += OnNewDocument;
            //App.WindowSelectionChange += OnWindowSelectionChange;
        }

        public static void QuitApplication()
        {
            if (App == null) return;
            App.Quit();
            App = null;
        }

        public static void OnWindowSelectionChange(Word.Selection selection)
        {
            if (String.IsNullOrWhiteSpace(selection.Text)) return;
            var s = "Text:" + selection.Text;
            s = s + "\n" + "Bold: " + selection.Font.Bold;
            s = s + "\n" + "Italic: " + selection.Font.Italic;
            MessageBox.Show(s);
        }

        public static void OnNewDocument(Word.Document doc)
        {
            MessageBox.Show("New Document");
        }

        private static void OnSize(Word.Document doc, Word.Window window)
        {
            //AdjustWindowPos();
        }

        public static void AdjustWindowPos()
        {
            var rec = Utils.GetWorkingArea();
            Win32.SetWindowPos(HWnd, IntPtr.Zero, rec.Left, rec.Top,
                               rec.Width, rec.Height - Program.frmMain.Height, 0);
        }

        private static void OnQuit()
        {
            App = null;
        }

        public static void Show()
        {
            if (App == null) { LoadApplication(); }
            if (App != null) App.Visible = true;
        }

        public static void Hide()
        {
            if (App != null) { App.Visible = false; }
        }
    }
}
